using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SumerCoreDevOps.Application.Permissions.Commands;
using SumerCoreDevOps.Application.Permissions.Queries;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Application.Dtos.Requests.Permissions;
namespace SumerCoreDevOps.ControlApi.Controllers;

/// <summary>
/// 权限管理 API
/// 提供权限的增删查、权限检查、按类别查询等功能
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PermissionController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<PermissionController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="mediator">MediatR 中介者</param>
    /// <param name="logger">日志记录器</param>
    public PermissionController(IMediator mediator, ILogger<PermissionController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有权限列表
    /// </summary>
    /// <returns>返回包含所有权限的列表,每个权限包括ID、名称、权限代码、类别、描述等完整信息;如果发生错误则返回500状态码和错误详情</returns>
    /// <response code="200">成功返回权限列表</response>
    /// <response code="500">服务器内部错误</response>
    [HttpGet]
    [ProducesResponseType(typeof(List<Permission>), 200)]
    public async Task<ActionResult<List<Permission>>> GetAllPermissions()
    {
        try
        {
            var permissions = await _mediator.Send(new GetAllPermissionsQuery());
            return Ok(permissions);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取权限列表失败");
            return StatusCode(500, new { message = "获取权限列表失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 获取权限详细信息
    /// </summary>
    /// <param name="permissionId">权限ID</param>
    /// <returns>返回指定权限的完整信息对象,包括权限ID、名称、权限代码、类别、描述、创建时间等字段;如果权限不存在则返回404状态码和提示信息;发生错误时返回500状态码和错误详情</returns>
    /// <response code="200">成功返回权限信息</response>
    /// <response code="404">权限不存在</response>
    /// <response code="500">服务器内部错误</response>
    [HttpGet("{permissionId}")]
    [ProducesResponseType(typeof(Permission), 200)]
    public async Task<ActionResult<Permission>> GetPermissionById(long permissionId)
    {
        try
        {
            var permission = await _mediator.Send(new GetPermissionByIdQuery(permissionId));
            if (permission == null)
            {
                return NotFound(new { message = "权限不存在" });
            }

            return Ok(permission);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取权限详细信息失败: PermissionId={PermissionId}", permissionId);
            return StatusCode(500, new { message = "获取权限信息失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 按类别获取权限列表
    /// </summary>
    /// <param name="category">权限类别（如：Workflow, Node, User, System）</param>
    /// <returns>返回指定类别下的所有权限列表,包含每个权限的完整信息(ID、名称、代码、类别、描述等);如果该类别下没有权限则返回空列表;发生错误时返回500状态码和错误详情</returns>
    /// <response code="200">成功返回权限列表</response>
    /// <response code="500">服务器内部错误</response>
    [HttpGet("category/{category}")]
    [ProducesResponseType(typeof(List<Permission>), 200)]
    public async Task<ActionResult<List<Permission>>> GetPermissionsByCategory(string category)
    {
        try
        {
            var permissions = await _mediator.Send(new GetPermissionsByCategoryQuery(category));
            return Ok(permissions);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "按类别获取权限失败: Category={Category}", category);
            return StatusCode(500, new { message = "获取权限失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 检查用户是否拥有指定权限
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="permissionCode">权限代码</param>
    /// <returns>返回包含用户ID、权限代码和布尔值hasPermission的对象,hasPermission为true表示用户拥有该权限,false表示没有该权限;发生错误时返回500状态码和错误详情</returns>
    /// <response code="200">返回权限检查结果</response>
    /// <response code="500">服务器内部错误</response>
    [HttpGet("check")]
    [ProducesResponseType(typeof(object), 200)]
    public async Task<ActionResult<object>> CheckUserPermission(
        [FromQuery] long userId,
        [FromQuery] string permissionCode)
    {
        try
        {
            var hasPermission = await _mediator.Send(new CheckUserPermissionQuery(userId, permissionCode));
            return Ok(new
            {
                userId,
                permissionCode,
                hasPermission
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查用户权限失败: UserId={UserId}, PermissionCode={PermissionCode}",
                userId, permissionCode);
            return StatusCode(500, new { message = "检查权限失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 创建新权限
    /// </summary>
    /// <param name="request">创建权限请求</param>
    /// <returns>返回201状态码和新创建的权限完整信息对象,包括自动生成的权限ID、权限名称、权限代码、类别、描述、创建时间等字段;如果权限代码已存在则返回400状态码和错误提示;发生其他错误时返回500状态码和错误详情</returns>
    /// <response code="201">成功创建权限</response>
    /// <response code="400">请求参数无效</response>
    /// <response code="500">服务器内部错误</response>
    [HttpPost]
    [ProducesResponseType(typeof(Permission), 201)]
    public async Task<ActionResult<Permission>> CreatePermission([FromBody] CreatePermissionRequest request)
    {
        try
        {
            var permission = await _mediator.Send(new CreatePermissionCommand(
                request.PermissionName,
                request.PermissionCode,
                request.Category,
                request.Description,
                request.CreatedBy
            ));

            return CreatedAtAction(nameof(GetPermissionById), new { permissionId = permission.Id }, permission);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建权限失败: PermissionName={PermissionName}", request.PermissionName);
            return StatusCode(500, new { message = "创建权限失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 删除权限
    /// </summary>
    /// <param name="permissionId">权限ID</param>
    /// <returns>返回200状态码和成功提示信息;如果权限是系统权限或正在被角色使用则返回400状态码和不能删除的原因;如果权限不存在则返回404状态码;发生错误时返回500状态码和错误详情</returns>
    /// <response code="200">权限删除成功</response>
    /// <response code="400">权限不能删除（如系统权限或被角色使用）</response>
    /// <response code="404">权限不存在</response>
    /// <response code="500">服务器内部错误</response>
    [HttpDelete("{permissionId}")]
    public async Task<ActionResult> DeletePermission(long permissionId)
    {
        try
        {
            await _mediator.Send(new DeletePermissionCommand(permissionId));
            return Ok(new { message = "权限删除成功" });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除权限失败: PermissionId={PermissionId}", permissionId);
            return StatusCode(500, new { message = "删除权限失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 获取所有权限类别列表
    /// </summary>
    /// <returns>返回系统中所有不重复的权限类别名称的字符串列表,按字母顺序排序;如果没有权限则返回空列表;发生错误时返回500状态码和错误详情</returns>
    /// <response code="200">成功返回权限类别列表</response>
    /// <response code="500">服务器内部错误</response>
    [HttpGet("categories")]
    [ProducesResponseType(typeof(List<string>), 200)]
    public async Task<ActionResult<List<string>>> GetPermissionCategories()
    {
        try
        {
            var permissions = await _mediator.Send(new GetAllPermissionsQuery());
            var categories = permissions
                .Where(p => !string.IsNullOrEmpty(p.Category))
                .Select(p => p.Category!)
                .Distinct()
                .OrderBy(c => c)
                .ToList();

            return Ok(categories);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取权限类别列表失败");
            return StatusCode(500, new { message = "获取权限类别失败", error = ex.Message });
        }
    }
}
